package com.jmx;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.log4j.Logger;

/**
 * Wrap properties simple introduction
 * 
 * <p>
 * detailed comment
 * 
 * @author zWX66194 2012-6-25
 * @see
 * @since 1.0
 */
public class PropertiesWrapper {
	private static final Logger LOGGER = Logger
			.getLogger(PropertiesWrapper.class);
	private Properties prop;
	private String fileName;

	public PropertiesWrapper(final String fileName) {
		this.fileName = fileName;
		prop = new Properties();
		InputStream in = null;
		try {
			in = new FileInputStream(Thread.currentThread()
					.getContextClassLoader().getResource(fileName).getPath());
			//in = this.getClass().getResourceAsStream(fileName); Only loading file when server starting if using getResourceAsStream.
			prop.load(in);
		} catch (IOException ex) {
			LOGGER.error(ex.getMessage());
			throw new RuntimeException(ex.getMessage());
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException ex) {
					LOGGER.error(ex.getMessage());
					throw new RuntimeException(ex.getMessage());
				}
			}
		}
	}

	public String getProperty(final String key) {
		return prop.getProperty(key);
	}

	public Object setProperty(final String key, final String value) {
		return prop.setProperty(key, value);
	}

	public void updateProperty(final String key, final String value,
			final String description) {
		prop.setProperty(key, value);
		store(this.fileName, description);
	}

	public void store(final String fileName, final String description) {
		OutputStream out = null;
		try {
			out = new FileOutputStream(Thread.currentThread()
					.getContextClassLoader().getResource(fileName).getPath());
			prop.store(out, description);
		} catch (FileNotFoundException ex) {
			LOGGER.error(ex.getMessage());
			throw new RuntimeException(ex.getMessage());
		} catch (IOException ex) {
			LOGGER.error(ex.getMessage());
			throw new RuntimeException(ex.getMessage());
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException ex) {
					LOGGER.error(ex.getMessage());
					throw new RuntimeException(ex.getMessage());
				}
			}
		}
	}
}